from django.contrib.auth import authenticate
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render,redirect,reverse
from django.views import View
from .models import User
from django.http import JsonResponse
from django.db import DatabaseError
from django import http

from django.contrib.auth import authenticate,login,logout


class RegisterView(View):
    def get(self, requests):
        return render(requests,'register.html')
    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        allow = request.POST.get('allow')
        try:
            user = User.objects.create_user(username=username, password=password)
        except DatabaseError as e:  # 如果链接数据库失败
            return render(request, 'register.html', {'register_errmsg': '注册失败'})
        # 响应注册结果
        login(request, user)
        return redirect(reverse('contents:index'))


class UsernameCountView(View):
    '''判断用户名是否重复'''
    def get(self,request,username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code':'0','errmsg': 'OK', 'count': count})

from django.http import HttpResponse, JsonResponse, HttpResponseForbidden

class LogView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        print('post')
        # 接受参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')
        if not all([username, password]):
            return HttpResponseForbidden('缺少必要参数')
        # 用authenticate校验
        user = authenticate(username=username, password=password)
        if not user:
            return render(request, 'login.html', {'register_errmsg': '用户名或密码错误'})
        # 状态保持
        login(request, user)
        # 设置状态保持的周期
        if remembered != 'on':
            # 没有记住用户：浏览器会话结束就过期
            request.session.set_expiry(0)
        else:
            # 记住用户：None表示两周后过期
            request.session.set_expiry(None)

        # 响应登录结果
        return http.HttpResponse('登录成功')

class LogoutView(View):
    def get(self,request):
        logout(request)
        return redirect(reverse('contents:index'))
